<template>
  <div class="users">
    <el-form :inline="true" :model="systemQuery" class="demo-form-inline">
      <el-form-item :label="formQuery.firstName">
        <el-input v-model="systemQuery.user_name" :placeholder="formQuery.firstPlaceholder"></el-input>
      </el-form-item>
      <el-form-item v-if="formQuery.show" :label="formQuery.secondName">
        <el-input v-model="systemQuery.phone" :placeholder="formQuery.secondPlaceholder"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button type="primary" @click="userAddVisible = true">用户新增</el-button>
        <el-button type="primary" @click="roleAddVisible = true">角色新增</el-button>
      </el-form-item>
    </el-form>
    <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="用户管理" name="system">
        <el-table
          :data="SystemUserList"
          style="width: 100%"
          v-loading="listLoading"
          :row-class-name="tableRowClassName">
          <el-table-column
            prop="id"
            label="序号"
            width="180">
          </el-table-column>
          <el-table-column
            prop="name"
            label="账号"
          >
          </el-table-column>
          <el-table-column
            prop="nickname"
            label="昵称"
            width="180">
          </el-table-column>
          <el-table-column
            prop="phone"
            label="手机号"
          >
          </el-table-column>
          <el-table-column label="是否管理员" class-name="status-col">
            <template v-slot="{row}">
              <el-tag :type="row.is_supper_admin | statusFilter">
                {{ row.is_supper_admin  | statusText }}
              </el-tag>

            </template>
          </el-table-column>
          <el-table-column label="用户角色" class-name="roles-col">
            <template v-slot="{row}">
              <el-tag type="info" v-for="(role,index) in row.roles" :key="index" style="margin-left: 5px">
                {{ role.role_name }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column
            prop="last_login_at"
            label="最后登录时间"
            width="180">
          </el-table-column>

          <el-table-column label="操作" align="center" min-width="70"
                           class-name="small-padding fixed-width">
            <template slot-scope="{row,$index}">
              <el-button type="primary" size="mini" @click="handleUpdate(row)">
                编辑
              </el-button>

              <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <Pagination v-show="systemUserTotal>0" :total="systemUserTotal" :page.sync="systemQuery.page_num"
                    :limit.sync="systemQuery.page_size" @pagination="getSystemUser"/>
      </el-tab-pane>

      <el-tab-pane label="小程序用户" name="mini">
        <el-table
          :data="MiniUserList"
          style="width: 100%"
          v-loading="listLoading"
          :row-class-name="tableRowClassName">
          <el-table-column
            prop="id"
            label="序号"
            width="180">
          </el-table-column>
          <el-table-column
            prop="name"
            label="账号"
          >
          </el-table-column>
          <el-table-column
            prop="nickname"
            label="昵称"
            width="180">
          </el-table-column>
          <el-table-column
            prop="phone"
            label="手机号"
          >
          </el-table-column>
          <el-table-column
            prop="openid"
            label="Openid"
          >
          </el-table-column>
          <el-table-column
            prop="last_login_ip"
            label="上次登陆IP"
          >
          </el-table-column>
          <el-table-column
            prop="last_login_at"
            label="最后登录时间"
          >
          </el-table-column>

          <!--          <el-table-column label="操作" align="center" min-width="70"-->
          <!--                           class-name="small-padding fixed-width">-->
          <!--            <template slot-scope="{row,$index}">-->
          <!--              <el-button type="primary" size="mini" @click="handleUpdate(row)">-->
          <!--                编辑-->
          <!--              </el-button>-->

          <!--              <el-button size="mini" type="danger" @click="handleDelete(row,$index)">-->
          <!--                删除-->
          <!--              </el-button>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
        </el-table>
        <Pagination v-show="miniUserTotal>0" :total="miniUserTotal" :page.sync="miniQuery.page_num"
                    :limit.sync="miniQuery.page_size" @pagination="getMiniUser"/>
      </el-tab-pane>
      <el-tab-pane label="角色列表" name="role">
        <el-table
          :data="roleList"
          style="width: 100%"
          v-loading="listLoading"
          :row-class-name="tableRowClassName">
          <el-table-column
            prop="id"
            label="序号"
           >
          </el-table-column>
          <el-table-column
            prop="name"
            label="角色名称"
          >
          </el-table-column>

          <el-table-column label="操作" align="center"
                           class-name="small-padding fixed-width">
            <template slot-scope="{row,$index}">
              <el-button type="primary" size="mini" @click="roleUpdate(row)">
                编辑
              </el-button>

              <el-button size="mini" type="danger" @click="roleDelete(row,$index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <el-dialog title="用户新增" :visible.sync="userAddVisible" width="20%">
      <el-form :model="userInfoTemp" label-position="right" label-width="120px">
        <el-form-item label="用户名称">
          <el-input style="width: 60%" v-model="userInfoTemp.nickname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input style="width: 60%" v-model="userInfoTemp.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input style="width: 60%" v-model="userInfoTemp.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="是否管理员">
          <el-radio v-model="userInfoTemp.is_supper_admin" :label="1">是</el-radio>
          <el-radio v-model="userInfoTemp.is_supper_admin" :label="0">否</el-radio>
        </el-form-item>
        <el-form-item label="角色选择(可多选)">
          <el-checkbox-group v-model="userInfoTemp.roles">
            <el-checkbox v-for="(item) in roleList" :label="item.id">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userAddVisible = false">取 消</el-button>
        <el-button type="primary" @click="userAdd()">确 定</el-button>
      </div>
    </el-dialog>

    <!--  角色新增 start   -->
    <el-dialog title="角色新增" :visible.sync="roleAddVisible" width="20%">
      <el-form :model="roleInfo">
        <el-form-item label="角色名称">
          <el-input style="width: auto" v-model="roleInfo.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色权限">
          <el-tree
            :data="PermissionParentList"
            show-checkbox
            node-key="id"
            ref="roleTree"
            highlight-current
            :default-expanded-keys="[1]"
            :default-checked-keys="[1]"
            style="margin-top: 5px;margin-left: 70px"
          >
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="roleAddVisible = false">取 消</el-button>
        <el-button type="primary" @click="roleAdd()">确 定</el-button>
      </div>
    </el-dialog>
    <!--  角色新增 end   -->

    <!--  用户编辑 start   -->
    <el-dialog title="用户编辑" :visible.sync="userUpdateVisible" width="20%">
      <el-form :model="userInfoTemp" label-position="right" label-width="120px">
        <el-form-item label="用户名称">
          <el-input style="width: 60%" v-model="userInfoTemp.nickname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input style="width: 60%" v-model="userInfoTemp.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="是否管理员">
          <el-radio v-model="userInfoTemp.is_supper_admin" :label="1">是</el-radio>
          <el-radio v-model="userInfoTemp.is_supper_admin" :label="0">否</el-radio>
        </el-form-item>
        <el-form-item label="角色选择(可多选)">
          <el-checkbox-group v-model="userInfoTemp.roles">
            <el-checkbox v-for="(item) in roleList" :label="item.id">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userUpdateVisible = false">取 消</el-button>
        <el-button type="primary" @click="userEdit()">确 定</el-button>
      </div>
    </el-dialog>
    <!--  用户编辑 end   -->

    <!--  角色编辑 start   -->
    <el-dialog title="角色编辑" :visible.sync="roleEditVisible" width="20%">
      <el-form :model="roleTempInfo">
        <el-form-item label="角色名称">
          <el-input style="width: auto" v-model="roleTempInfo.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色权限">
          <el-tree
            :data="PermissionParentList"
            show-checkbox
            node-key="id"
            ref="roleTreeEdit"
            highlight-current

            :default-checked-keys=roleTempInfo.permission

            style="margin-top: 5px;margin-left: 70px"
          >
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="roleEditVisible = false">取 消</el-button>
        <el-button type="primary" @click="roleEdit()">确 定</el-button>
      </div>
    </el-dialog>
    <!--  角色编辑 end   -->

  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import {SystemUserFetch, SystemUserUpdate, SystemUserAdd, SystemUserDelete} from "@/api/user";
import waves from "@/directive/waves";
import {deletePermission, fetchParentList, updatePermission} from "@/api/permission";
import {rolesAdd, getRoles, showRoles, roleUpdate, roleDelete} from "@/api/roles";


export default {

  directives: {waves}, filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success', 2: 'info', 0: 'danger'
      }
      return statusMap[status]
    }, typeFilter(type) {
      return type;
    }, statusText(status) {
      const statusMapText = {
        1: '是', 0: '否'
      }
      console.log(status)
      return statusMapText[status]
    }
  },

  name: 'Users',

  components: {Pagination},
  mixins: [],

  props: {},

  data() {
    return {
      activeName: 'system',
      SystemUserList: [],
      MiniUserList: [],
      SystemRoleList: [],
      systemUserTotal: 0,
      miniUserTotal: 0,
      listLoading: false,
      roleEditVisible: false,
      formQuery: {
        firstName: '用户名',
        firstPlaceholder: '请输入用户名',
        show: true,
        secondName: '手机号',
        secondPlaceholder: '请输入手机号'
      },
      systemQuery: {
        type: 'system',
        user_name: '',
        phone: '',
        page_num: 1,
        page_size: 10
      },

      miniQuery: {
        type: 'mini',
        user_name: '',
        phone: '',
        page_num: 1,
        page_size: 10
      },
      roleQuery: {
        type: 'role',
        user_name: '',
        phone: '',
        page_num: 1,
        page_size: 10
      },

      roleInfo: {
        name: '',
        permission: []
      },

      userInfoTemp: {
        nickname: '',
        phone: '',
        is_supper_admin: '',
        password: '',
        roles: []
      },
      roleAddVisible: false,
      userAddVisible: false,
      userUpdateVisible: false,
      PermissionParentList: [],
      roleList: [],
      roleTempInfo:{
        id:'',
        name:'',
        permission:[]
      }

    }
  },

  computed: {},

  watch: {},

  created() {
    console.log(this.activeName)


    this.getSystemUser()
    this.getParentList()
    this.getRoleList();
  },

  methods: {
    handleClick(tab, event) {
      console.log(123)
      if (this.activeName === "mini") {
        this.formQuery.firstName = '微信昵称'
        this.formQuery.firstPlaceholder = '请输入微信昵称'
        this.formQuery.show = true
        this.formQuery.secondName = '手机号'
        this.formQuery.secondPlaceholder = ' 请输入手机号'
        this.systemQuery.type = this.activeName
        this.getMiniUser()
      } else if (this.activeName === 'role') {
        this.formQuery.firstName = '角色名称'
        this.formQuery.firstPlaceholder = '请输入角色名称'
        this.formQuery.show = false
      } else {
        this.systemQuery.type = this.activeName
        this.getSystemUser()
      }
      console.log(tab, event);
    },
    roleUpdate(row){
      this.listLoading = true
      this.roleTempInfo.permission = [];
      showRoles(row.id).then(response=>{
        this.listLoading = false
        this.roleTempInfo.id = response.data.data.id
        this.roleTempInfo.name = response.data.data.name
        for (var key in response.data.data.permissions) {
          this.roleTempInfo.permission.push(response.data.data.permissions[key].id)
        }
        this.$nextTick(() => {
          this.$refs.roleTreeEdit.setCheckedKeys( this.roleTempInfo.permission)
        })
        this.roleEditVisible = true
      })

      console.log("角色详情===>",this.roleTempInfo)

    },
    roleDelete(row){
      console.log(row)
      roleDelete(row.id).then(response=>{
        if (response.code === 200) {
          this.userUpdateVisible = false

          this.$notify({
            title: '成功', message: '删除成功', type: 'success', duration: 2000
          })

          this.getRoleList();
        } else {
          this.$notify({
            title: '失败', message: response.message, type: 'error', duration: 2000
          })
        }
      })
    },
    tableRowClassName({row, rowIndex}) {
      if (rowIndex === 1) {
        return 'warning-row';
      } else if (rowIndex === 3) {
        return 'success-row';
      }
      return '';
    },
    getSystemUser() {
      this.listLoading = true
      SystemUserFetch(this.systemQuery).then(response => {
        this.SystemUserList = response.data.data
        this.systemUserTotal = response.data.page_info.count
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
        console.log(response)
      })
    },
    getRoleList() {
      getRoles().then(response => {
        this.roleList = response.data.data
      })
    },
    getMiniUser() {
      console.log('查询小程序用户')
      this.listLoading = true
      SystemUserFetch(this.systemQuery).then(response => {
        this.MiniUserList = response.data.data
        this.miniUserTotal = response.data.page_info.count
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
        console.log(response)
      })
    },
    onSubmit() {
      if (this.activeName == "system") {
        this.getSystemUser()
      } else {
        this.getMiniUser()
      }

    },
    userAdd() {
      console.log(this.userInfoTemp)
      SystemUserAdd(this.userInfoTemp).then((response => {
        console.log(response)
        if (response.code === 200) {
          this.userUpdateVisible = false

          this.$notify({
            title: '成功', message: '修改成功', type: 'success', duration: 2000
          })
          this.getSystemUser();
        } else {
          this.$notify({
            title: '失败', message: response.message, type: 'error', duration: 2000
          })
        }
        this.getSystemUser();

      }))
    },
    userEdit() {
      SystemUserUpdate(this.userInfoTemp).then(response => {
        console.log(response)
        if (response.code === 200) {
          this.userUpdateVisible = false

          this.$notify({
            title: '成功', message: '修改成功', type: 'success', duration: 2000
          })
          this.getSystemUser();
        } else {
          this.$notify({
            title: '失败', message: response.message, type: 'error', duration: 2000
          })
        }
      })
    },
    roleEdit(){
      this.roleTempInfo.permission =  this.$refs.roleTreeEdit.getCheckedKeys()
      let arr = this.roleTempInfo.permission
      if (!this.roleTempInfo.name) {
        this.$message({
          message: '请输入角色名',
          type: 'warning'
        });
        return false
      }
      if (!arr.includes(8)) {
        this.$message({
          message: '请赋予角色基本权限 [用户登录] ',
          type: 'warning'
        });
        return false
      }
      if (!arr.includes(9)) {
        this.$message({
          message: '请赋予角色基本权限 [用户退出登录] ',
          type: 'warning'
        });
        return false
      }
      if (!arr.includes(10)) {
        this.$message({
          message: '请赋予角色基本权限  [用户刷新token] ',
          type: 'warning'
        });
        return false
      }
      if (!arr.includes(11)) {
        this.$message({
          message: '请赋予角色基本权限  [获取账号信息]',
          type: 'warning'
        });
        return false
      }
      if (arr.length < 1) {
        this.$message({
          message: '请选择角色权限',
          type: 'warning'
        });
        return false
      }
      roleUpdate(this.roleTempInfo.id,this.roleTempInfo).then(response=>{
        if (response.code === 200) {
          this.roleEditVisible = false
          this.$notify({
            title: '成功', message: '修改成功', type: 'success', duration: 2000
          })

        } else {
          this.$notify({
            title: '失败', message: response.message, type: 'error', duration: 2000
          })
        }
      })

    },
    handleUpdate(row) {
      console.log(row)
      this.userInfoTemp = Object.assign({}, row) // copy obj
      if (row.roles.length > 0) {
        this.userInfoTemp.roles = []
        for (var key in row.roles) {
          this.userInfoTemp.roles.push(row.roles[key].role_id)
        }

      } else {
        this.userInfoTemp.roles = [];
      }

      this.userInfoTemp.roles
      this.userUpdateVisible = true
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          console.log(tempData)
          console.log(tempData.id)
          updatePermission(tempData.id, tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功', message: '更新成功', type: 'success', duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      SystemUserDelete(row.id).then(() => {
        this.$notify({
          title: '成功', message: '删除成功', type: 'success', duration: 2000
        })
        this.getSystemUser()
      })
    },
    roleAdd() {
      let arr = this.$refs.roleTree.getCheckedKeys()
      if (!this.roleInfo.name) {
        this.$message({
          message: '请输入角色名',
          type: 'warning'
        });
        return false
      }
      if (!arr.includes(8)) {
        this.$message({
          message: '请赋予角色基本权限 [用户登录] ',
          type: 'warning'
        });
        return false
      }
      if (!arr.includes(9)) {
        this.$message({
          message: '请赋予角色基本权限 [用户退出登录] ',
          type: 'warning'
        });
        return false
      }
      if (!arr.includes(10)) {
        this.$message({
          message: '请赋予角色基本权限  [用户刷新token] ',
          type: 'warning'
        });
        return false
      }
      if (!arr.includes(11)) {
        this.$message({
          message: '请赋予角色基本权限  [获取账号信息]',
          type: 'warning'
        });
        return false
      }
      if (arr.length < 1) {
        this.$message({
          message: '请选择角色权限',
          type: 'warning'
        });
        return false
      }
      this.roleInfo.permission = arr;
      rolesAdd(this.roleInfo).then(response => {
        if (response.code === 200) {
          this.$message({
            message: '角色新增成功',
            type: 'success'
          });
        } else {
          this.$message({
            message: response.message,
            type: 'warning'
          });
        }
      })
      setTimeout(() => {
        this.roleAddVisible = false
      }, 1.5 * 1000)


    },
    getParentList() {
      this.listLoading = true
      fetchParentList(this.listQuery).then(response => {
        this.PermissionParentList = response.data
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },


  }
}
</script>
<style scoped lang="scss">
.users {
  padding: 32px;
  background-color: rgb(240, 242, 245);
  position: relative;

  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
}
</style>
